package top.canyue.eca_manager.mapper;

import org.apache.ibatis.annotations.*;
import top.canyue.eca_manager.bean.User;
import top.canyue.eca_manager.provider.UserProvider;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {
    @Select(value = "SELECT id,name,phone,admin,createTime,updateTime FROM user WHERE id = #{id} AND isDelete= 0")
    User findById(String id);

    @Select(value = "SELECT id,name,phone,admin,createTime,updateTime FROM user WHERE isDelete= 0 AND name LIKE CONCAT('%',#{name},'%') ORDER BY #{orders} DESC LIMIT #{offset},#{fetchSize}")
    List<User> findByName(String name, String orders, Integer offset, Integer fetchSize);

    @Select(value = "SELECT id,name,phone,admin,createTime,updateTime FROM user WHERE isDelete= 0 ORDER BY #{orders} DESC LIMIT #{offset},#{fetchSize}")
    List<User> findAll(String orders, Integer offset, Integer fetchSize);

    @Select(value = "SELECT COUNT(id) FROM user WHERE isDelete= 0 AND name LIKE CONCAT('%',#{name},'%') ")
    Integer getUserCountByName(String name);

    @Select(value = "SELECT COUNT(id) FROM user WHERE isDelete= 0 ")
    Integer getUserCountAll();

    @Insert(value = "INSERT INTO user(id,name,passwd,phone,admin,isDelete,createTime) VALUES( #{id} , #{name}, #{passwd}, #{phone}, 0, 0, NOW() )")
    Integer addUser(User user);

    @Select(value = "SELECT id,name,phone,admin FROM user WHERE isDelete = 0 AND (BINARY name = #{idOrName} OR BINARY id  = #{idOrName} OR phone = #{idOrName}) AND BINARY passwd = #{passwd} AND isDelete= 0")
    User login(String idOrName,String passwd);

    @UpdateProvider(type = UserProvider.class, method = "updateUserInfo")
    Integer updateUserInfo(User user);

    @Update(value = "UPDATE user SET passwd= #{newPasswd},updateTime = NOW() WHERE id = #{id} AND BINARY passwd = #{oldPasswd}")
    Integer updateUserPasswd(String id, String oldPasswd, String newPasswd);

    @Update(value = "UPDATE user SET isDelete = 1,updateTime = NOW() WHERE id = #{id} AND isDelete = 0")
    Integer deleteUser(String id);

    @Update(value = "UPDATE user SET admin = #{admin},updateTime = NOW() WHERE id = #{id}")
    Integer updateUserAdmin(String id, Integer admin);

    @Select(value = "SELECT COUNT(id) FROM user WHERE isDelete = 0")
    Integer getUserCount();

    @Select(value="SELECT COUNT(id) FROM user WHERE isDelete = 0 AND DATE_FORMAT(createTime,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')")
    Integer getUserCountByMount();

    @Select(value = "SELECT id, name FROM user WHERE NOT isDelete")
    List<Map<String, String>> getAllUserName();

}
